package com.xmad.ksadutils.AdSDK.AdMold.OnCallback;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.xmad.ksadutils.AdSDK.AdBase.TTAdManagerHolder;
import com.xmad.ksadutils.AdSDK.Interface.AdOnLoad;
import com.xmad.ksadutils.AdSDK.Utlis.RxLogUtils;
import com.xmad.ksadutils.AdSDK.Utlis.Tool;

import java.util.List;


public class PGloadBannerExpressAd implements AdOnLoad {
    private volatile static PGloadBannerExpressAd mInstance;
    int Width;
    public PGloadBannerExpressAd setWidth(int width) {
        Width = width;
        return this;
    }


    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    private float px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxValue / scale + 0.5f);
    }

    private void bindAdListener(TTNativeExpressAd ad, final FrameLayout mExpressContainer, Activity context) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
                Log.e("广告被点击","广告被点击");
            }

            @Override
            public void onAdShow(View view, int type) {
                Log.e("onAdShow","onAdShow");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                Log.d("TAGxx", msg + " code:" + code);
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                //返回view的宽高 单位 dp
                Log.d("TAGxx", "渲染成功");
                //mExpressContainer.removeAllViews();
                mExpressContainer.addView(view);
                mExpressContainer.setPadding(10,10,10,10);
            }
        });
        //dislike设置
        bindDislike(ad, false, mExpressContainer, context);
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return;
        }
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
                Log.d("TAGxx", "点击开始下载");
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {

            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                Log.d("TAGxx", "下载暂停，点击继续");
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                Log.d("TAGxx", "下载失败，点击重新下载");
            }

            @Override
            public void onInstalled(String fileName, String appName) {
                Log.d("TAGxx", "安装完成，点击图片打开");
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                Log.d("TAGxx", "点击安装");
            }
        });
    }

    /**
     * 设置广告的不喜欢, 注意：强烈建议设置该逻辑，如果不设置dislike处理逻辑，则模板广告中的 dislike区域不响应dislike事件。
     *
     * @param ad
     * @param customStyle 是否自定义样式，true:样式自定义
     */
    private void bindDislike(TTNativeExpressAd ad, boolean customStyle, final FrameLayout mExpressContainer, Activity context) {
        //  使用默认模板中默认dislike弹出样式
        ad.setDislikeCallback(context, new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onShow() {

            }

            @Override
            public void onSelected(int i, String s, boolean b) {
                Log.d("TAGxx", "点击 " + s);
                //用户选择不喜欢原因后，移除广告展示
                mExpressContainer.removeAllViews();
                mExpressContainer.setVisibility(View.GONE);
            }

            @Override
            public void onCancel() {
                Log.d("TAGxx", "点击取消 ");
            }



        });
    }


    @Override
    public void noCallback(Long id, Activity activity, FrameLayout frameLayout) {

    }

    @Override
    public void noCallback(String id, Activity activity, FrameLayout frameLayout) {
        TTAdManager ttAdManager = TTAdManagerHolder.get();
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        // TTAdManagerHolder.get().requestPermissionIfNecessary(context);
        //step3:创建TTAdNative对象,用于调用广告请求接口
        final TTAdNative TTAdNative = ttAdManager.createAdNative(activity);
        frameLayout.removeAllViews();
        float expressViewWidth = 350;
        float expressViewHeight = 350;
        if (Width==0){
            Width= Tool.getScreenWidth(activity);
        }
        expressViewWidth = px2dip(activity, Width);
        expressViewHeight = 0; //高度设置为0,则高度会自适应
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(id)
                .setSupportDeepLink(true).setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight) //期望模板广告view的size,单位dp
                .setImageAcceptedSize(640, 320)//这个参数设置即可，不影响模板广告的size
                .build();
        //step5:请求广告，对请求回调的广告作渲染处理
        TTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                frameLayout.removeAllViews();
                RxLogUtils.e(message);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0) {
                    return;
                }
                TTNativeExpressAd mTTAd = ads.get(0);
                bindAdListener(mTTAd, frameLayout, activity);
                mTTAd.render();
            }
        });
    }
}
